package org.qiyu.live.framework.redis.starter.key;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 *  条件注入类
 */
public class RedisKeyLoadMatch implements Condition {
    private static final Logger log = LoggerFactory.getLogger(RedisKeyLoadMatch.class);
    private static final String PREFIX = "qiyulive";

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        String appName = context.getEnvironment().getProperty("spring.application.name");
        if (appName == null) {
            log.error("无法找到应用程序的\"spring.application.name\"");
            return false;
        }

        try {
            Field className = metadata.getClass().getDeclaredField("className");
            className.setAccessible(true);
            String keyBuilderName = (String) className.get(metadata);
            List<String> splitList = Arrays.asList(keyBuilderName.split("\\."));
            String classSimpleName = PREFIX + splitList.get(splitList.size() - 1).toLowerCase();
            boolean matchStatus = classSimpleName.contains(appName.replaceAll("-", ""));
            log.info("加载类名 {}, 匹配状态 {}", keyBuilderName, matchStatus);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        return true;

    }
}
